const express = require('express');
const app = express();
app.listen(3000,()=>{
    console.log('服务器已开启');
})


// 连接mysql
const mysql = require('mysql');
const con = mysql.createConnection({
    host:'localhost',
    port:3306,
    user:'root',
    password:'root',
    database:'demo'
})

con.connect();

// 接参中间件
app.use(express.urlencoded({extended:false}));

// 注册逻辑
app.post('/register',(req,res)=>{
    // 接参 
    let {username,password} = req.body;

    // 判断用户名是否存在
    let sql = `SELECT * FROM member WHERE username = '${username}'`;
    con.query(sql,(err,result)=>{
        // console.log(err,result);
        if(err){
            res.send({code:500,msg:err});
            return;
        }


        // 判断用户名是否存在
        if(result.length > 0){
            res.send({code:400,msg:'用户名已存在'});
            return;
        }


        // 不存在添加到表中
        let sql = `insert into member (username,password) values ('${username}','${password}')`

        con.query(sql,(err,result)=>{
            if(err){
                res.send({code:500,msg:err});
                return;
            }

            if(result.insertId > 0){
                res.send({code:200,msg:'注册成功'})
            }else{
                res.send({code:400,msg:'请稍后再试'})
            }

        })
        
    })
    
})